<template>
  <div class="homework-edit-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="page-title-section">
          <span class="title-icon">✏️</span>
          <h1 class="page-title">编辑作业</h1>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <div class="container">
        <!-- 作业基本信息 -->
        <div class="form-section">
          <div class="form-row">
            <div class="form-group">
              <label>标题</label>
              <input 
                v-model="homeworkForm.title" 
                type="text" 
                placeholder="请输入标题"
                class="form-input large"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>开始时间</label>
              <input 
                v-model="homeworkForm.startTime" 
                type="text" 
                placeholder="请输入时间"
                class="form-input"
              />
            </div>
            
            <div class="form-group">
              <label>结束时间</label>
              <input 
                v-model="homeworkForm.endTime" 
                type="text" 
                placeholder="请输入时间"
                class="form-input"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group full-width">
              <label>描述</label>
              <textarea 
                v-model="homeworkForm.description" 
                class="form-textarea"
                rows="8"
                placeholder="请输入作业描述..."
              ></textarea>
            </div>
          </div>
        </div>

        <!-- 题目选择区域 -->
        <div class="questions-section">
          <div class="section-tabs">
            <button 
              :class="['tab-btn', { active: activeTab === 'select' }]"
              @click="activeTab = 'select'"
            >
              我的试题
            </button>
            <button 
              :class="['tab-btn', { active: activeTab === 'public' }]"
              @click="activeTab = 'public'"
            >
              公开题库
            </button>
          </div>

          <!-- 搜索栏 -->
          <div v-if="activeTab === 'select' || activeTab === 'public'" class="search-filter-bar">
            <input 
              type="text" 
              v-model="searchKeyword" 
              placeholder="搜索题目标题..."
              class="search-input"
              @keyup.enter="searchQuestions"
            >
              <select v-model="searchDifficulty" class="difficulty-select">
                <option value="">全部难度</option>
                <option value="1">难度 1</option>
                <option value="2">难度 2</option>
                <option value="3">难度 3</option>
                <option value="4">难度 4</option>
                <option value="5">难度 5</option>
                <option value="6">难度 6</option>
              </select>
            <button @click="searchQuestions" class="search-btn">
              <i class="fas fa-search"></i>
              搜索
            </button>
            <button @click="resetSearch" class="reset-btn">
              <i class="fas fa-redo"></i>
              重置
            </button>
          </div>

          <!-- 题目列表 - 我的试题和公开题库共用 -->
          <div v-if="activeTab === 'select' || activeTab === 'public'" class="questions-list">
            <div class="questions-table-container">
              <table class="questions-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>标题</th>
                    <th>类型</th>
                    <th>权重</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-if="availableQuestions.length === 0">
                    <td colspan="5" class="empty-row">暂无试题数据</td>
                  </tr>
                  <tr v-for="question in availableQuestions" :key="question.id" class="table-row">
                    <td>{{ question.id }}</td>
                    <td class="title-cell">{{ question.title }}</td>
                    <td>{{ question.type }}</td>
                    <td>{{ question.weight }}</td>
                    <td class="action-cell">
                      <button @click="addQuestionToHomework(question)" class="add-btn">+</button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- 我的试题分页控件 -->
            <div v-if="activeTab === 'select' && myQuestionsPagination.total > 0" class="pagination">
              <button 
                @click="changeMyQuestionsPage(myQuestionsPagination.current - 1)" 
                :disabled="myQuestionsPagination.current === 1"
                class="page-btn"
              >
                <i class="fas fa-chevron-left"></i>
                上一页
              </button>
              <span class="page-info">
                第 {{ myQuestionsPagination.current }} / {{ myQuestionsPagination.pages }} 页
                (共 {{ myQuestionsPagination.total }} 条)
              </span>
              <button 
                @click="changeMyQuestionsPage(myQuestionsPagination.current + 1)" 
                :disabled="myQuestionsPagination.current === myQuestionsPagination.pages"
                class="page-btn"
              >
                下一页
                <i class="fas fa-chevron-right"></i>
              </button>
              <div class="page-jump">
                <span class="jump-label">跳转到</span>
                <input 
                  type="number" 
                  v-model.number="myQuestionsPagination.jumpPage"
                  @keyup.enter="jumpToMyQuestionsPage"
                  min="1"
                  :max="myQuestionsPagination.pages"
                  class="jump-input"
                />
                <span class="jump-label">页</span>
                <button @click="jumpToMyQuestionsPage" class="jump-btn">
                  <i class="fas fa-arrow-right"></i>
                  跳转
                </button>
              </div>
            </div>
            
            <!-- 公开题库分页控件 -->
            <div v-if="activeTab === 'public' && publicQuestionsPagination.total > 0" class="pagination">
              <button 
                @click="changePublicQuestionsPage(publicQuestionsPagination.current - 1)" 
                :disabled="publicQuestionsPagination.current === 1"
                class="page-btn"
              >
                <i class="fas fa-chevron-left"></i>
                上一页
              </button>
              <span class="page-info">
                第 {{ publicQuestionsPagination.current }} / {{ publicQuestionsPagination.pages }} 页
                (共 {{ publicQuestionsPagination.total }} 条)
              </span>
              <button 
                @click="changePublicQuestionsPage(publicQuestionsPagination.current + 1)" 
                :disabled="publicQuestionsPagination.current === publicQuestionsPagination.pages"
                class="page-btn"
              >
                下一页
                <i class="fas fa-chevron-right"></i>
              </button>
              <div class="page-jump">
                <span class="jump-label">跳转到</span>
                <input 
                  type="number" 
                  v-model.number="publicQuestionsPagination.jumpPage"
                  @keyup.enter="jumpToPublicQuestionsPage"
                  min="1"
                  :max="publicQuestionsPagination.pages"
                  class="jump-input"
                />
                <span class="jump-label">页</span>
                <button @click="jumpToPublicQuestionsPage" class="jump-btn">
                  <i class="fas fa-arrow-right"></i>
                  跳转
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 本次作业题目 -->
        <div class="homework-questions-section">
          <div class="section-header">
            <span class="section-number">2</span>
            <span class="section-title">📝 本次作业题</span>
            <span class="questions-count">{{ selectedQuestions.length }} 道试题</span>
          </div>

          <div class="homework-questions-table">
            <table class="questions-table">
              <thead>
                <tr>
                  <th>序号</th>
                  <th>标题</th>
                  <th>类型</th>
                  <th>权重</th>
                  <th>分数</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="selectedQuestions.length === 0">
                  <td colspan="6" class="empty-row">
                    暂无选择作业题目
                    <br />
                    <span class="tip">请从 <span class="highlight">我的试题</span> 选择题目</span>
                  </td>
                </tr>
                <tr v-for="(question, index) in selectedQuestions" :key="question.id" class="table-row">
                  <td>{{ index + 1 }}</td>
                  <td class="title-cell">{{ question.title }}</td>
                  <td>{{ question.type }}</td>
                  <td>{{ question.weight }}</td>
                  <td class="score-cell">
                    <input 
                      v-model.number="question.score" 
                      type="number" 
                      min="0"
                      step="1"
                      placeholder="分数"
                      class="score-input"
                    />
                  </td>
                  <td class="action-cell">
                    <button @click="removeQuestionFromHomework(index)" class="remove-btn">移除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- 选择团队（已移除需求，不再在编辑页面选择班级） -->

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button @click="goBack" class="cancel-btn">取消</button>
          <button @click="saveHomework" class="save-btn">保存</button>
          <button @click="publishHomework" class="publish-btn">更新并发布</button>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getHomeworkDetail, updateHomework as updateHomeworkAPI } from '@/api/homework'
import { getCurrentUserId } from '@/utils/userIdUtils'
import { teamApi } from '@/api/team'
import logger from '../utils/logger.js'

export default {
  name: 'HomeworkEdit',
  setup() {
    // Vue Router
    const router = useRouter()
    
    // 响应式数据
    const activeTab = ref('select')
    const availableQuestions = ref([])
    const selectedQuestions = ref([])
    const selectedTeams = ref([])
    const editingHomeworkId = ref(null)
    const homeworkId = ref(null)
    
    // 搜索条件
    const searchKeyword = ref('')
    const searchDifficulty = ref('')
    
    // 我的试题分页数据
    const myQuestionsPagination = reactive({
      current: 1,
      size: 10,
      total: 0,
      pages: 0,
      jumpPage: 1  // 跳转页码输入
    })
    
    // 公开题库分页数据
    const publicQuestionsPagination = reactive({
      current: 1,
      size: 10,
      total: 0,
      pages: 0,
      jumpPage: 1  // 跳转页码输入
    })
    
    // 监听 activeTab 变化，切换时加载对应题目
    watch(activeTab, (newTab) => {
      logger.log('📑 [HomeworkEdit] 标签页切换:', newTab)
      if (newTab === 'select') {
        // 切换到我的试题时重置为第1页
        myQuestionsPagination.current = 1
        myQuestionsPagination.jumpPage = 1
        loadQuestions(newTab, 1)
      } else if (newTab === 'public') {
        // 切换到公开题库时重置为第1页
        publicQuestionsPagination.current = 1
        publicQuestionsPagination.jumpPage = 1
        loadQuestions(newTab, 1)
      }
    })

    // 表单数据
    const homeworkForm = reactive({
      title: '',
      startTime: '',
      endTime: '',
      publishTime: '2025-09-12 20:57:52',
      mode: 'ACM',
      description: '',
      totalScore: 100
    })

    // 团队数据
    const teams = ref([])
    const isLoadingTeams = ref(false)

    // 模拟可用题目数据
    const mockQuestions = [
      {
        id: '44930',
        title: '信号拒绝',
        type: 'goc',
        weight: '简单题',
        price: '0.0元'
      },
      {
        id: '44926',
        title: '挂灯笼',
        type: 'goc',
        weight: '简单题',
        price: '0.0元'
      },
      {
        id: '44924',
        title: '小明',
        type: 'goc',
        weight: '简单题',
        price: '0.0元'
      },
      {
        id: '44921',
        title: '红苹果',
        type: 'goc',
        weight: '简单题',
        price: '0.0元'
      },
      {
        id: '32979',
        title: '勾股定理',
        type: 'goc',
        weight: '简单题',
        price: '0.0元'
      }
    ]

    // 方法
    const loadQuestions = async (tab = null, page = 1) => {
      const currentTab = tab || activeTab.value
      logger.log('📚 [HomeworkEdit] 开始加载题目，标签页:', currentTab, '页码:', page)
      
      try {
        availableQuestions.value = []
        
        if (currentTab === 'select') {
          // 加载我的试题（带分页）
          logger.log('📖 [HomeworkEdit] 调用我的试题API: /goc/homework/myCreatQuestion，第', page, '页')
          
          // 构建查询参数
          const params = {
            page: page,
            size: myQuestionsPagination.size
          }
          
          // 添加搜索条件
          if (searchKeyword.value) {
            params.keyword = searchKeyword.value
            logger.log('🔍 [HomeworkEdit] 搜索关键词:', searchKeyword.value)
          }
          if (searchDifficulty.value) {
            params.difficulty = parseInt(searchDifficulty.value)
            logger.log('🔍 [HomeworkEdit] 搜索难度:', searchDifficulty.value)
          }
          
          const api = await import('@/api/config')
          const response = await api.default.get('/goc/homework/myCreatQuestion', {
            params: params,
            timeout: 15000
          })
          
          logger.log('✅ [HomeworkEdit] 我的试题API响应:', response)
          
          if (response && response.data) {
            // 格式化题目数据
            const questions = Array.isArray(response.data) ? response.data : (response.data.records || [])
            availableQuestions.value = questions.map(q => ({
              id: q.id || q.testQuestionId,
              title: q.questionName || q.title,
              type: q.questionType ? `type${q.questionType}` : 'goc',
              weight: q.difficulty ? `难度${q.difficulty}` : '简单题'
            }))
            
            // 更新分页信息
            if (response.data.current !== undefined) {
              myQuestionsPagination.current = response.data.current || page
              myQuestionsPagination.total = response.data.total || 0
              myQuestionsPagination.pages = response.data.pages || Math.ceil(response.data.total / myQuestionsPagination.size)
              myQuestionsPagination.jumpPage = myQuestionsPagination.current
            }
            
            logger.log('✅ [HomeworkEdit] 我的试题加载成功，共', availableQuestions.value.length, '题')
            logger.log('📄 [HomeworkEdit] 分页详情:', myQuestionsPagination)
          }
        } else if (currentTab === 'public') {
          // 加载公开题库（带分页）
          logger.log('📖 [HomeworkEdit] 调用公开题库API: /goc/testQuestion/list，第', page, '页')
          
          // 构建查询参数
          const params = {
            isPublic: 1,
            page: page,
            size: publicQuestionsPagination.size
          }
          
          // 添加搜索条件
          if (searchKeyword.value) {
            params.keyword = searchKeyword.value
            logger.log('🔍 [HomeworkEdit] 搜索关键词:', searchKeyword.value)
          }
          if (searchDifficulty.value) {
            params.difficulty = parseInt(searchDifficulty.value)
            logger.log('🔍 [HomeworkEdit] 搜索难度:', searchDifficulty.value)
          }
          
          const api = await import('@/api/config')
          const response = await api.default.get('/goc/testQuestion/list', {
            params: params,
            timeout: 15000
          })
          
          logger.log('✅ [HomeworkEdit] 公开题库API响应:', response)
          
          if (response && response.data) {
            // 格式化题目数据
            const questions = Array.isArray(response.data) ? response.data : (response.data.records || [])
            availableQuestions.value = questions.map(q => ({
              id: q.id || q.testQuestionId,
              title: q.questionName || q.title,
              type: q.questionType ? `type${q.questionType}` : 'goc',
              weight: q.difficulty ? `难度${q.difficulty}` : '简单题'
            }))
            
            // 更新分页信息
            if (response.data.current !== undefined) {
              publicQuestionsPagination.current = response.data.current || page
              publicQuestionsPagination.total = response.data.total || 0
              publicQuestionsPagination.pages = response.data.pages || Math.ceil(response.data.total / publicQuestionsPagination.size)
              publicQuestionsPagination.jumpPage = publicQuestionsPagination.current
            }
            
            logger.log('✅ [HomeworkEdit] 公开题库加载成功，共', availableQuestions.value.length, '题')
            logger.log('📄 [HomeworkEdit] 分页详情:', publicQuestionsPagination)
          }
        }
      } catch (error) {
        logger.error('❌ [HomeworkEdit] 加载题目失败:', error)
        availableQuestions.value = []
      }
    }
    
    // 搜索题目
    const searchQuestions = () => {
      logger.log('🔍 [HomeworkEdit] 搜索题目')
      // 重置到第一页
      if (activeTab.value === 'select') {
        myQuestionsPagination.current = 1
        myQuestionsPagination.jumpPage = 1
      } else if (activeTab.value === 'public') {
        publicQuestionsPagination.current = 1
        publicQuestionsPagination.jumpPage = 1
      }
      loadQuestions(activeTab.value, 1)
    }
    
    // 重置搜索
    const resetSearch = () => {
      logger.log('🔄 [HomeworkEdit] 重置搜索条件')
      searchKeyword.value = ''
      searchDifficulty.value = ''
      if (activeTab.value === 'select') {
        myQuestionsPagination.current = 1
        myQuestionsPagination.jumpPage = 1
      } else if (activeTab.value === 'public') {
        publicQuestionsPagination.current = 1
        publicQuestionsPagination.jumpPage = 1
      }
      loadQuestions(activeTab.value, 1)
    }
    
    // 切换我的试题页码
    const changeMyQuestionsPage = (page) => {
      if (page < 1 || page > myQuestionsPagination.pages) return
      logger.log('📄 [HomeworkEdit] 切换我的试题到第', page, '页')
      loadQuestions('select', page)
    }
    
    // 跳转到我的试题指定页码
    const jumpToMyQuestionsPage = () => {
      const page = parseInt(myQuestionsPagination.jumpPage)
      if (isNaN(page) || page < 1 || page > myQuestionsPagination.pages) {
        alert(`请输入有效的页码（1-${myQuestionsPagination.pages}）`)
        myQuestionsPagination.jumpPage = myQuestionsPagination.current
        return
      }
      logger.log('🎯 [HomeworkEdit] 跳转我的试题到第', page, '页')
      changeMyQuestionsPage(page)
    }
    
    // 切换公开题库页码
    const changePublicQuestionsPage = (page) => {
      if (page < 1 || page > publicQuestionsPagination.pages) return
      logger.log('📄 [HomeworkEdit] 切换公开题库到第', page, '页')
      loadQuestions('public', page)
    }
    
    // 跳转到公开题库指定页码
    const jumpToPublicQuestionsPage = () => {
      const page = parseInt(publicQuestionsPagination.jumpPage)
      if (isNaN(page) || page < 1 || page > publicQuestionsPagination.pages) {
        alert(`请输入有效的页码（1-${publicQuestionsPagination.pages}）`)
        publicQuestionsPagination.jumpPage = publicQuestionsPagination.current
        return
      }
      logger.log('🎯 [HomeworkEdit] 跳转公开题库到第', page, '页')
      changePublicQuestionsPage(page)
    }

    const loadHomeworkData = async () => {
      try {
        // 从URL路径参数或localStorage获取作业ID
        const urlParams = router.currentRoute.value.params
        const localStorageId = localStorage.getItem('editingHomeworkId')
        
        logger.log('🔍 [HomeworkEdit] URL参数:', urlParams)
        logger.log('🔍 [HomeworkEdit] localStorage ID:', localStorageId)
        logger.log('🔍 [HomeworkEdit] 当前路由:', router.currentRoute.value)
        
        homeworkId.value = urlParams.id || localStorageId
        
        logger.log('📝 [HomeworkEdit] 开始加载作业数据...')
        logger.log('🆔 [HomeworkEdit] 最终作业ID:', homeworkId.value)
        
        if (homeworkId.value) {
          // 调用API获取作业详情
          const response = await getHomeworkDetail(homeworkId.value)
          
          logger.log('✅ [HomeworkEdit] API响应:', response)
          
          if (response && response.code === 0 && response.data) {
            const homeworkData = response.data
            editingHomeworkId.value = homeworkData.id
            
            // 填充表单数据
            homeworkForm.title = homeworkData.title || ''
            homeworkForm.startTime = homeworkData.startTime || ''
            homeworkForm.endTime = homeworkData.endTime || ''
            homeworkForm.publishTime = homeworkData.publishTime || '2025-09-12 20:57:52'
            homeworkForm.mode = homeworkData.mode || 'ACM'
            homeworkForm.description = homeworkData.description || ''
            homeworkForm.totalScore = homeworkData.totalScore || 100
            
            // 填充已选择的题目
            if (homeworkData.questions && Array.isArray(homeworkData.questions)) {
              selectedQuestions.value = homeworkData.questions.map(q => ({
                id: q.testQuestionId || q.id,
                title: q.questionName || q.title || q.questionTitle,  // 优先使用questionName
                type: q.type || 'toc',
                weight: q.weight || '简单题',
                price: q.price || '0.0元',
                score: q.score || 10,
                sortOrder: q.sortOrder || 0
              }))
              logger.log('📝 [HomeworkEdit] 第一个题目名称:', selectedQuestions.value[0]?.title)
            }
            
            // 填充已选团队（如果后端有返回）
            if (homeworkData.teams && Array.isArray(homeworkData.teams)) {
              selectedTeams.value = homeworkData.teams
            }
            
            logger.log('✅ [HomeworkEdit] 作业数据加载完成:', homeworkData)
            logger.log('📊 [HomeworkEdit] 已选择题目数量:', selectedQuestions.value.length)
          } else {
            throw new Error('API返回数据格式不正确')
          }
        } else {
          logger.warn('⚠️ [HomeworkEdit] 未找到作业ID')
        }
      } catch (error) {
        logger.error('❌ [HomeworkEdit] 加载作业数据失败:', error)
        
        // 如果API调用失败，尝试从localStorage加载
        const editingHomework = JSON.parse(localStorage.getItem('editingHomework') || '{}')
        if (editingHomework.id) {
          editingHomeworkId.value = editingHomework.id
          homeworkForm.title = editingHomework.title || ''
          homeworkForm.startTime = editingHomework.startTime || ''
          homeworkForm.endTime = editingHomework.endTime || ''
          homeworkForm.publishTime = editingHomework.publishTime || '2025-09-12 20:57:52'
          homeworkForm.mode = editingHomework.mode || 'ACM'
          homeworkForm.description = editingHomework.description || ''
          selectedQuestions.value = editingHomework.questions || []
          selectedTeams.value = editingHomework.teams || []
          logger.log('⚠️ [HomeworkEdit] 使用localStorage数据作为备用')
        }
      }
    }

    const addQuestionToHomework = (question) => {
      const exists = selectedQuestions.value.find(q => q.id === question.id)
      if (!exists) {
        selectedQuestions.value.push({ ...question, score: 0 })
        logger.log('添加题目到作业:', question)
      } else {
        alert('该题目已经添加过了')
      }
    }

    const removeQuestionFromHomework = (index) => {
      selectedQuestions.value.splice(index, 1)
    }

    // 获取用户ID - 从JWT令牌中解析
    const getUserId = () => {
      try {
        const token = localStorage.getItem('token')
        if (token) {
          const parts = token.split('.')
          if (parts.length === 3) {
            const payload = parts[1]
            const paddedPayload = payload + '='.repeat((4 - payload.length % 4) % 4)
            const decodedPayload = atob(paddedPayload.replace(/-/g, '+').replace(/_/g, '/'))
            
            const fixedJsonString = decodedPayload.replace(
              /"(id|userId|teamId|questionId|homeworkId|newsId)":\s*(\d{15,})/g,
              '"$1":"$2"'
            )
            
            const payloadObj = JSON.parse(fixedJsonString)
            
            if (payloadObj.claims && payloadObj.claims.id) {
              const userId = payloadObj.claims.id
              logger.log('👤 [HomeworkEdit] 从JWT令牌获取用户ID:', userId, '类型:', typeof userId)
              return userId
            }
          }
        }
        
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        return userInfo.userId || userInfo.id || ''
      } catch (error) {
        logger.error('❌ [HomeworkEdit] 解析JWT令牌失败:', error)
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        return userInfo.userId || userInfo.id || ''
      }
    }
    
    // 加载我的班级
    const loadMyTeams = async () => {
      isLoadingTeams.value = true
      
      try {
        const userId = getUserId()
        if (!userId) {
          alert('用户信息获取失败，请重新登录')
          return
        }
        
        logger.log('🏫 [HomeworkEdit] 开始加载我的班级')
        logger.log('👤 [HomeworkEdit] 用户ID:', userId)
        
        const response = await teamApi.findById(userId)
        
        logger.log('✅ [HomeworkEdit] 班级信息获取成功:', response)
        
        if (response && response.code === 0) {
          const teamData = response.data
          
          if (teamData) {
            if (teamData.id) {
              teams.value = [{
                id: teamData.id,
                number: teamData.id,
                name: teamData.teamName || teamData.name || '未命名班级',
                description: teamData.description,
                memberCount: teamData.memberCount || 0
              }]
            }
            else if (Array.isArray(teamData)) {
              teams.value = teamData.map(team => ({
                id: team.id,
                number: team.id,
                name: team.teamName || team.name || '未命名班级',
                description: team.description,
                memberCount: team.memberCount || 0
              }))
            }
            
            logger.log('🏫 [HomeworkEdit] 班级列表:', teams.value)
            logger.log(`✅ [HomeworkEdit] 加载成功，共找到 ${teams.value.length} 个班级`)
          } else {
            teams.value = []
            if (window.$message?.info) {
              window.$message.info('暂无班级信息')
            } else {
              alert('暂无班级信息')
            }
          }
        } else {
          const errorMsg = response?.message || '获取班级信息失败'
          logger.error('❌ [HomeworkEdit] 业务错误:', errorMsg)
          if (window.$message?.error) {
            window.$message.error(errorMsg)
          } else {
            alert(errorMsg)
          }
        }
      } catch (error) {
        logger.error('❌ [HomeworkEdit] 加载班级失败:', error)
        
        const errorMessage = error.response?.data?.message || error.message || '加载班级失败，请重试'
        if (window.$message?.error) {
          window.$message.error(errorMessage)
        } else {
          alert(errorMessage)
        }
      } finally {
        isLoadingTeams.value = false
      }
    }
    
    const toggleTeam = (teamId) => {
      const index = selectedTeams.value.indexOf(teamId)
      if (index > -1) {
        selectedTeams.value.splice(index, 1)
      } else {
        selectedTeams.value.push(teamId)
      }
    }

    const saveHomework = () => {
      updateHomework('未发布')
    }

    const publishHomework = () => {
      if (selectedQuestions.value.length === 0) {
        alert('请至少选择一道题目')
        return
      }
      // 编辑页不再选择班级，保留原有班级关联（无需校验）
      
      updateHomework('已发布')
    }

    const updateHomework = async (status) => {
      try {
        // 验证必填字段
        if (!homeworkForm.title.trim()) {
          alert('请输入作业标题')
          return
        }
        
        if (!homeworkForm.startTime) {
          alert('请选择开始时间')
          return
        }
        
        if (!homeworkForm.endTime) {
          alert('请选择结束时间')
          return
        }
        
        if (selectedQuestions.value.length === 0) {
          alert('请至少选择一道题目')
          return
        }
        
        // 构建更新数据
        const updateData = {
          id: editingHomeworkId.value,
          title: homeworkForm.title.trim(),
          description: homeworkForm.description || '',
          teacherId: getCurrentUserId(), // 添加正确的教师ID
          // 编辑页不修改班级归属，不传 teamIds，后端沿用原有班级设置
          startTime: homeworkForm.startTime,
          endTime: homeworkForm.endTime,
          totalScore: homeworkForm.totalScore || 100,
          questions: selectedQuestions.value.map((q, index) => ({
            testQuestionId: q.id,
            sortOrder: index + 1,
            score: q.score || 0  // 使用用户设置的分数，默认为0
          }))
        }
        
        logger.log('📝 [HomeworkEdit] 开始更新作业...')
        logger.log('🆔 [HomeworkEdit] 作业ID:', editingHomeworkId.value)
        logger.log('📊 [HomeworkEdit] 更新数据:', updateData)
        logger.log('📊 [HomeworkEdit] 状态:', status)
        
        // 调用API更新作业
        const response = await updateHomeworkAPI(editingHomeworkId.value, updateData)
        
        logger.log('✅ [HomeworkEdit] API响应:', response)
        
        if (response && response.code === 0) {
          // 🔥 更新成功（code = 0）
          logger.log('✅ [HomeworkEdit] 作业更新成功（code = 0）');
          
          // 移除成功提示，直接跳转以改善用户体验
          // const successMsg = response.message || `作业已${status === '已发布' ? '更新并发布' : '保存'}成功`;
          // alert(successMsg)
          
          // 清除编辑数据
          localStorage.removeItem('editingHomework')
          localStorage.removeItem('editingHomeworkId')
          
          // 设置刷新标记，让作业列表页面知道需要刷新数据
          localStorage.setItem('homeworkListNeedsRefresh', 'true')
          
          // 跳转回作业列表页面
          window.location.href = '#/assign-homework'
        } else {
          throw new Error(response?.message || '更新失败')
        }
        
      } catch (error) {
        logger.error('❌ [HomeworkEdit] 更新作业失败:', error)
        
        // 🔥 根据后端返回的实际错误信息显示
        let errorMsg = '更新作业失败，请重试'
        
        // 尝试从各种可能的位置获取后端错误信息
        if (error.response?.data?.message) {
          errorMsg = error.response.data.message
        } else if (error.data?.message) {
          errorMsg = error.data.message
        } else if (error.message) {
          errorMsg = error.message
        }
        
        logger.error('❌ [HomeworkEdit] 显示错误消息:', errorMsg)
        alert('❌ ' + errorMsg)
      }
    }

    const goBack = () => {
      // 清除编辑数据
      localStorage.removeItem('editingHomework')
      localStorage.removeItem('editingHomeworkId')
      // 返回作业列表页面
      window.location.href = '#/assign-homework'
    }



    // 生命周期
    onMounted(async () => {
      await loadQuestions('select')  // 默认加载我的试题
      await loadHomeworkData()
      // 编辑页不再自动加载班级信息
    })

    return {
      activeTab,
      availableQuestions,
      selectedQuestions,
      selectedTeams,
      homeworkForm,
      teams,
      isLoadingTeams,
      myQuestionsPagination,
      publicQuestionsPagination,
      searchKeyword,
      searchDifficulty,
      changeMyQuestionsPage,
      jumpToMyQuestionsPage,
      changePublicQuestionsPage,
      jumpToPublicQuestionsPage,
      addQuestionToHomework,
      removeQuestionFromHomework,
      toggleTeam,
      loadMyTeams,
      saveHomework,
      publishHomework,
      searchQuestions,
      resetSearch,
      goBack
    }
  }
}
</script>

<style scoped>
.homework-edit-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px;
}

/* 页面头部样式 */
.page-header {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-title-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-icon {
  font-size: 24px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0;
  font-weight: 600;
}

/* 主要内容区域 */
.main-content {
  max-width: 1400px;
  margin: 0 auto;
}

.container {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 表单样式 */
.form-section {
  margin-bottom: 30px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  align-items: end;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.form-group.large {
  flex: 2;
}

.form-group.full-width {
  flex: 1;
  width: 100%;
}

.form-group label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-input,
.form-select,
.form-textarea {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #4CAF50;
}

.form-textarea {
  resize: vertical;
  min-height: 120px;
}

/* 编辑器工具栏 */
.editor-toolbar {
  display: flex;
  gap: 5px;
  padding: 8px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px 4px 0 0;
  margin-bottom: -1px;
}

.toolbar-btn {
  padding: 4px 8px;
  border: 1px solid #ccc;
  background: white;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.toolbar-btn:hover {
  background: #f0f0f0;
}

/* 题目选择区域 */
.questions-section {
  margin-bottom: 30px;
}

.section-tabs {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  background: #ff9800;
  padding: 10px 15px;
  border-radius: 6px;
}

.tab-btn {
  background: #ff9800;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.tab-btn.active {
  background: #e68900;
}

.tab-btn:hover {
  background: #e68900;
}

/* 搜索过滤栏 */
.search-filter-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  align-items: center;
}

.search-filter-bar .search-input {
  flex: 1;
  padding: 10px 15px;
  border: 2px solid #e1e8ed;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.search-filter-bar .search-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.search-filter-bar .difficulty-select {
  padding: 10px 15px;
  border: 2px solid #e1e8ed;
  border-radius: 6px;
  font-size: 14px;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 150px;
}

.search-filter-bar .difficulty-select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.search-filter-bar .search-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.search-filter-bar .search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.5);
}

.search-filter-bar .reset-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #6c757d, #5a6268);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 8px rgba(108, 117, 125, 0.3);
}

.search-filter-bar .reset-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(108, 117, 125, 0.5);
}

.tab-info {
  margin-left: auto;
  color: white;
  font-size: 14px;
}

.count {
  font-weight: bold;
  color: #fff;
}

/* 题目表格 */
.questions-table-container,
.homework-questions-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.questions-table {
  width: 100%;
  border-collapse: collapse;
}

.questions-table th {
  background: #4CAF50;
  color: white;
  padding: 12px 15px;
  text-align: left;
  font-weight: 500;
  font-size: 14px;
}

.questions-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  color: #333;
}

.table-row:hover {
  background: #f9f9f9;
}

.title-cell {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.action-cell {
  text-align: center;
}

.add-btn {
  background: #4CAF50;
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-btn:hover {
  background: #45a049;
}

.remove-btn {
  background: #f44336;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.remove-btn:hover {
  background: #da190b;
}

.empty-row {
  text-align: center;
  color: #999;
  padding: 40px 20px;
  font-style: italic;
}

.tip {
  font-size: 12px;
  color: #666;
}

.highlight {
  color: #ff9800;
  font-weight: bold;
}

/* 本次作业题目 */
.homework-questions-section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #4CAF50;
  color: white;
  padding: 12px 20px;
  border-radius: 6px;
  margin-bottom: 15px;
}

.section-number {
  background: white;
  color: #4CAF50;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
}

.questions-count {
  margin-left: auto;
  font-size: 14px;
}

/* 团队选择 */
.team-section {
  margin-bottom: 30px;
}

.team-section .section-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
}

.load-teams-btn {
  padding: 10px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.load-teams-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
}

.load-teams-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.team-grid {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.team-card {
  border: 2px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 120px;
}

.team-card:hover {
  border-color: #4CAF50;
}

.team-card.selected {
  border-color: #4CAF50;
  background: #f0f8f0;
}

.team-number {
  font-size: 24px;
  font-weight: bold;
  color: #666;
  margin-bottom: 5px;
}

.team-name {
  font-size: 14px;
  color: #333;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 30px;
}

.cancel-btn,
.save-btn,
.publish-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.2s;
}

.cancel-btn {
  background: #757575;
  color: white;
}

.cancel-btn:hover {
  background: #616161;
}

.save-btn {
  background: #4CAF50;
  color: white;
}

.save-btn:hover {
  background: #45a049;
}

.publish-btn {
  background: #ff9800;
  color: white;
}

.publish-btn:hover {
  background: #e68900;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .homework-edit-page {
    padding: 10px;
  }
  
  .container {
    padding: 20px;
  }
  
  .form-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .section-tabs {
    flex-wrap: wrap;
  }
  
  .team-grid {
    justify-content: center;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }

  /* 移动端分页样式优化 */
  .pagination {
    flex-direction: column;
    gap: 12px;
    padding: 15px;
  }

  .page-info {
    order: -1;
    padding: 0;
  }

  .page-jump {
    padding-left: 0;
    border-left: none;
    padding-top: 10px;
    border-top: 2px solid #e0e0e0;
    width: 100%;
    justify-content: center;
  }

  .jump-input {
    width: 70px;
  }
}

/* 分页控件样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 15px;
  padding: 20px;
  margin-top: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.page-btn {
  padding: 8px 16px;
  background: #ff9800;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
  box-shadow: 0 2px 4px rgba(255, 152, 0, 0.3);
}

.page-btn:hover:not(:disabled) {
  background: #f57c00;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(255, 152, 0, 0.4);
}

.page-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  opacity: 0.6;
  box-shadow: none;
  transform: none;
}

.page-info {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  padding: 0 15px;
  white-space: nowrap;
}

/* 页码跳转样式 */
.page-jump {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-left: 15px;
  border-left: 2px solid #e0e0e0;
}

.jump-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.jump-input {
  width: 60px;
  padding: 6px 10px;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  text-align: center;
  transition: all 0.3s;
}

.jump-input:focus {
  outline: none;
  border-color: #ff9800;
  box-shadow: 0 0 0 3px rgba(255, 152, 0, 0.1);
}

.jump-input:hover {
  border-color: #ff9800;
}

/* 移除数字输入框的上下箭头 */
.jump-input::-webkit-inner-spin-button,
.jump-input::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.jump-input[type=number] {
  -moz-appearance: textfield;
}

.jump-btn {
  padding: 6px 14px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 600;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
  box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
}

.jump-btn:hover {
  background: linear-gradient(135deg, #5568d3, #6a3f8f);
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(102, 126, 234, 0.4);
}

.jump-btn:active {
  transform: translateY(0);
}

/* 分数输入框样式 */
.score-cell {
  padding: 8px;
}

.score-input {
  width: 80px;
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
  transition: all 0.2s;
}

.score-input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.score-input:hover {
  border-color: #999;
}
</style> 